package main

import (
	"github.com/micro/cli/v2"
	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/auth"
	pb "github.com/micro/go-micro/v2/auth/service/proto"
	"github.com/morphyguo/demo/commons"

	//"github.com/micro/go-micro/v2/authapi/token"
	//"github.com/micro/go-micro/v2/authapi/token/jwt"
	"github.com/micro/go-micro/v2/config/cmd"
	log "github.com/micro/go-micro/v2/logger"
	_ "github.com/micro/go-plugins/registry/eureka/v2"
	accountsHandler "github.com/morphyguo/demo/srv/auth/handler/accounts"
	authHandler "github.com/morphyguo/demo/srv/auth/handler/auth"
	rulesHandler "github.com/morphyguo/demo/srv/auth/handler/rules"
)
var (
	// Name of the service
	// Address of the service
)
func main()  {

	_ = log.Init(log.WithFields(map[string]interface{}{"service": "auth"}))

	// Init plugins
	//for _, p := range Plugins() {
	//	p.Init(ctx)
	//}

	//if len(ctx.String("address")) > 0 {
	//	Address = ctx.String("address")
	//}
	//if len(Address) > 0 {
	//	srvOpts = append(srvOpts, micro.Address(Address))
	//}

	// Init plugins
	//for _, p := range Plugins() {
	//	p.Init(ctx)
	//}

	// setup the handlers
	authH := &authHandler.Auth{}
	ruleH := &rulesHandler.Rules{}
	accountH := &accountsHandler.Accounts{}

	// setup the authapi handler to use JWTs
	//pubKey := ctx.String("auth_public_key")
	//privKey := ctx.String("auth_private_key")
	//if len(pubKey) > 0 || len(privKey) > 0 {
	//	authH.TokenProvider = jwt.NewTokenProvider(
	//		token.WithPublicKey(pubKey),
	//		token.WithPrivateKey(privKey),
	//	)
	//}

	st := *cmd.DefaultCmd.Options().Store

	// set the handlers store
	authH.Init(auth.Store(st))
	ruleH.Init(auth.Store(st))
	accountH.Init(auth.Store(st))

	service := micro.NewService(micro.Name(commons.NsSrvAuth))
	service.Init()
	// register handlers
	_ = pb.RegisterAuthHandler(service.Server(), authH)
	_ = pb.RegisterRulesHandler(service.Server(), ruleH)
	_ = pb.RegisterAccountsHandler(service.Server(), accountH)

	// run service
	if err := service.Run(); err != nil {
		log.Fatal(err)
	}

}

func authFromContext(ctx *cli.Context) auth.Auth {
	//if ctx.Bool("platform") {
	//	os.Setenv("MICRO_PROXY", "service")
	//	os.Setenv("MICRO_PROXY_ADDRESS", "proxy.micro.mu:443")
	//	return srvAuth.NewAuth()
	//}

	return *cmd.DefaultCmd.Options().Auth
}

